package com.yan;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.net.URI;

/**
 * TODO
 *
 * @Author: 汪焰
 * @Date: 2021/7/5 23:32
 */
@ComponentScan("com.yan")
@Configuration
@EnableRabbit//启用监听模式//在xml中可以使用<rabbit:annotation-driven/>启动@RabbitListener注解
public class RabbitConfig {

    //连接工程
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory(URI.create("amqp://root:root@1.116.195.238:5672/%2f"));
        return factory;
    }

    //RabbitTemplate
    @Bean
    @Autowired
    public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(factory);
        return rabbitTemplate;
    }

    //RabbitAdmin
    @Bean
    @Autowired
    public RabbitAdmin rabbitAdmin(ConnectionFactory factory) {
        RabbitAdmin rabbitTemplate = new RabbitAdmin(factory);
        return rabbitTemplate;
    }

    //Queue
    @Bean
    public Queue queue() {
        Queue queue = QueueBuilder.nonDurable("queue.anno.name.yan").build();
        return queue;
    }

    //SimpleRabbitListenerContainerFactory
    @Bean("rabbitListenerContainerFactory")
    @Autowired
    public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
//        (注释掉 会有严格的先后顺序)
//        factory.setConcurrentConsumers(10);
//        (注释掉 会有严格的先后顺序)
//        factory.setMaxConcurrentConsumers(15);
        //按照批次消费消息(注释掉 会有严格的先后顺序)
//        factory.setBatchSize(10);
        return factory;
    }


}
